#!/usr/bin/env coffee
import platform from '@/config/platform.mjs'

process.on(
  'exit'
  =>
    app.quit()
    return
)

# 只允许启动一次
if not app.requestSingleInstanceLock()
  app.quit()
  process.exit(0)

import DEV from '@/config/dev.js'
if not DEV
  do =>
    Sentry = await import('@sentry/electron')
    Sentry.init({
      dsn: 'https://54c0fbe278e049c8a9635fc0fa612836@sentry.dalukuankuan.com/6'
    })
    return

import {app, ipcMain, globalShortcut}  from "electron"


import destroy from './destroy.coffee'

app.commandLine.appendSwitch('webrtc-max-cpu-consumption-percentage', '100')
app.commandLine.appendSwitch('js-flags', '--expose_gc --max-old-space-size=512')
# app.commandLine.appendSwitch('disable-features', 'HardwareMediaKeyHandling,MediaSessionService')
#app.commandLine.appendSwitch('disable-features', 'SameSiteByDefaultCookies')
#app.commandLine.appendSwitch('webrtc-max-cpu-consumption-percentage', '100')

import os from "os"
import $on from '../lib/on.coffee'
import Tray from './tray.coffee'
import devtool from './devtool.coffee'
import * as ipc from './ipc.coffee'
import main from './ipc/main.coffee'
import TITLE from '@/config/title.js'
#app.commandLine.appendSwitch('lang', 'zh-CN')

do =>
# platform = os.platform()
#  if platform.startsWith 'win'
#    if os.release().startsWith("6.1") # window 7
#      app.disableHardwareAcceleration()


  main()

  if platform == 'darwin'
    app.dock?.hide()
  else if platform == 'win32'
    null
    ###
    app.setUserTasks [
      {
        iconPath: execPath
        iconIndex: 0
        program: execPath
        title: TITLE
        arguments: ""
        description: ""
      }
    ]
    ###

  _handle = (k, v)=>
    if v instanceof Function
      #if not isPackaged
      ipcMain.handle k.join('.'), (e,args)=>
        v.apply(e,args)

    for [name,func] from Object.entries v
      _handle [...k, name], func

    return

  for [k,v] from Object.entries ipc
    _handle([k], v)

  Tray()
  devtool()
  return

#https://stackoverflow.com/questions/42524606/how-to-get-windows-version-using-node-js

$on app, {

###
"window-all-closed": =>
  if process.platform != "darwin"
    app.quit()
  return
###

"second-instance": =>
  show = true
  BrowserWindow.getAllWindows().forEach (w)=>
    url = w.webContents.getURL()
    try
      {hash} = new URL url
    catch err
      return
    if hash.startsWith '#recbar'
      show = false
    return
  if show
    main()
  return

activate: main
}
